# -*- coding: utf-8 -*-

import os, socket, logging, redis #, memcache
from wechat_sdk import WechatConf
from wechat_sdk import WechatBasic

# wechatpy
from wechatpy.client import WeChatClient
from wechatpy.session.redisstorage import RedisStorage
from redis import Redis

gettext = lambda s: s
DATA_DIR = os.path.dirname(os.path.dirname(__file__))

log = logging.getLogger(__name__)
log.setLevel(logging.INFO)

PROD_SERVER_HOST_NAME = 'cn.woodchat.info'
TST_SERVER_HOST_NAME = ['testsrv']
DEV_HOST_NAME = ['sya.rmbp.bak']

ClAWLER_SCHEDULE_INTERVAL = 90

"""
Django settings for disn project.

Generated by 'django-admin startproject' using Django 1.8.17.

For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PROJECT_PATH = os.path.join(os.path.dirname(__file__),'').replace('\\','/')


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'j4ptxv56rg#tw&+gh)(#8y#&6jv4^3e&f0yfe^m@#gclj_=#&='

# SECURITY WARNING: don't run with debug turned on in production!
# DEBUG = True
DEBUG = False
if socket.gethostname() == PROD_SERVER_HOST_NAME:
    DEBUG  = False
    print ('Prod Server : [%s] is starting...' % socket.gethostname())
else:
    DEBUG  = True
    print ('Dev Server : [%s] is starting...' % socket.gethostname())

ALLOWED_HOSTS = ['*']


LOGIN_URL = '/account/signin/'
LOGIN_REDIRECT_URL = '/account/dashboard/'
LOGOUT_URL = '/account/logout/'

DATETIME_FORMAT =  'Y-m-d H:i:s'
DATE_FORMAT = 'Y-m-d'
TIME_FORMAT = 'H:i:s'

# Application definition

DISN_HTTP_URL = 'https://www.disnlink.com'
ROOT_URL = 'https://www.ztm.me'
MEMCACHED_SERVER = '127.0.0.1:11211'
WECHAT_ADMIN_USER_ID = 'jezhang'

# redis_instance = redis.Redis(host='127.0.0.1', port=6379)
if DEBUG:
    redis_url = 'redis://:Schenker123@bw.ztm.me:6379/0'
    redis_pool = redis.ConnectionPool(host='bw.ztm.me', port=6379, db=0, password='Schenker123')
else:
    redis_url = 'redis://:Schenker123@127.0.0.1:6379/0'
    redis_pool = redis.ConnectionPool(host='127.0.0.1', port=6379, db=0, password='Schenker123')
redis_instance = redis.Redis(connection_pool=redis_pool)


YUNPIAN_APIKEY = '9570e92902b854ddeafaac795c76d660'

# Wechat SDK config
TOKEN = 'disn2017link'
APPID = 'wxf78da8e222832632'
APPSECRET = 'cf303d729143e28c12e91ddff588e0f3'
ENCODING_AES_KEY = 'zaUaSHaSxO2Q96fTHgenMaH6S1ryJsawvN3RmRhjctk'

BOOK_SUBSCRIPTION_APPID = 'wx2eade028d698136f'
BOOK_SUBSCRIPTION_TOKEN = 'booksubscription2018'
BOOK_SUBSCRIPTION_APPSECRET = '33a63a600a61ce3a39821a4ea8a85e58'
BOOK_SUBSCRIPTION_ENCODING_AES_KEY = 'bQCYdFbQnFNmxVfLiGELls0A9xLLXQhwLDF9jUgkIO0'

BOOK_SERVICE_APPID = 'wx093410d83dc79561'
BOOK_SERVICE_TOKEN = 'bookservice2018'
BOOK_SERVICE_APPSECRET = '8ec38425dcd0d64ab4e2a3b95849478c'
BOOK_SERVICE_ENCODING_AES_KEY = 'rCvGECYY9akmXUEd82jjGd9ydTWcJ6qiTGLBsLhXxQ6'


# wechatpy initilize wechat_client
# redis_client = Redis.from_url('redis://127.0.0.1:6379/0')
redis_client = redis.Redis(connection_pool=redis_pool, password='Schenker123')
session_interface = RedisStorage(
    redis_client,
    prefix="wechatpy"
)

def get_wechat_client():
    log.info('function get_wechat_client reload')
    wechat_client = WeChatClient(APPID, APPSECRET, session=session_interface)
    log.info('wechat_client idendification: %d' %id(wechat_client))
    return wechat_client

def get_book_subscription_wechat_client():
    log.info('function get_book_subscription_wechat_client reload')
    get_book_subscription_wechat_client = WeChatClient(BOOK_SUBSCRIPTION_APPID, BOOK_SUBSCRIPTION_APPSECRET, session=session_interface)
    log.info('get_book_subscription_wechat_client idendification: %d' %id(get_book_subscription_wechat_client))
    return get_book_subscription_wechat_client

def get_book_service_wechat_client():
    log.info('function get_book_service_wechat_client reload')
    get_book_service_wechat_client = WeChatClient(BOOK_SERVICE_APPID, BOOK_SERVICE_APPSECRET, session=session_interface)
    log.info('get_book_service_wechat_client idendification: %d' %id(get_book_service_wechat_client))
    return get_book_service_wechat_client

# JOS configuration
JD_APP_KEY      = '81DE177DCC79674210F9C31FB8B61FCE'
JD_APP_SECRET   = 'e111e1954e1c4bbb9307eb15fb846128'
JD_ACCESS_TOKEN = '8f72d787be394e74b491cc8b8cd4796foddi' # CREATED ON 2019/02/18
'''
def get_wechat_conf():
    conf = WechatConf(
        token=TOKEN,
        appid=APPID,
        appsecret=APPSECRET,
        encrypt_mode='normal',  # 可选项：normal/compatible/safe，分别对应于 明文/兼容/安全 模式
        encoding_aes_key=ENCODING_AES_KEY,  # 如果传入此值则必须保证同时传入 token, appid
        access_token=get_access_token(),
        access_token_expires_at=get_access_token_expires_at(),
        jsapi_ticket=get_jsapi_ticket(),
        jsapi_ticket_expires_at=get_jsapi_ticket_expires_at(),
        # access_token_getfunc=get_access_token_function,
        # access_token_setfunc=set_access_token_function,
        # jsapi_ticket_getfunc=get_jsapi_ticket_function,
        # jsapi_ticket_setfunc=set_jsapi_ticket_function,
    )
    return conf

def get_access_token():
    return mc.get('disn_access_token')
def get_access_token_expires_at():
    return mc.get('disn_access_token_expires_at')
def get_jsapi_ticket():
    return mc.get('disn_jsapi_ticket')
def get_jsapi_ticket_expires_at():
    return mc.get('disn_jsapi_ticket_expires_at')

def get_wechat_instance():
    # print('function get_wechat_instance() reload.')
    try:
        wechat = WechatBasic(conf=get_wechat_conf())
        if not (get_access_token() and get_access_token_expires_at() and get_jsapi_ticket() and get_jsapi_ticket_expires_at()):
            mc.set(key='disn_access_token', val=wechat.get_access_token()['access_token'],time=7200)
            mc.set(key='disn_access_token_expires_at', val=wechat.get_access_token()['access_token_expires_at'],time=7200)
            mc.set(key='disn_jsapi_ticket', val=wechat.get_jsapi_ticket()['jsapi_ticket'],time=7200)
            mc.set(key='disn_jsapi_ticket_expires_at', val=wechat.get_jsapi_ticket()['jsapi_ticket_expires_at'],time=7200)
        return wechat
    except BaseException as e:
        log.error('wechat initialized failure')
        logging.exception(e)
        return None
'''

# SMS webservice

# QINIU

QN_AK = 'RkySaUVzhdgWrbA9EzeigXdT0EuxQA9GYf8Ew4sq'
QN_SK = 'P1DWRN3U0TUOoUUCzE6qNEg984L56WtCA7A1sbs7'

# mc = memcache.Client([MEMCACHED_SERVER], debug=0)
# print('initialize new memcache instance : %d' %id(mc))

ROOT_URLCONF = 'disn.urls'

WSGI_APPLICATION = 'disn.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases

# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/

LANGUAGE_CODE = 'zh'

TIME_ZONE = 'Asia/Shanghai'

USE_I18N = True

USE_L10N = True

USE_TZ = False


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/

STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(DATA_DIR, 'media')
STATIC_ROOT = os.path.join(DATA_DIR, 'static')

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'disn', 'static'),
)
SITE_ID = 1


TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'disn', 'templates'),],
        'OPTIONS': {
            'context_processors': [
                'django.contrib.auth.context_processors.auth',
    'django.contrib.messages.context_processors.messages',
    'django.core.context_processors.i18n',
    'django.core.context_processors.debug',
    'django.core.context_processors.request',
    'django.core.context_processors.media',
    'django.core.context_processors.csrf',
    'django.core.context_processors.tz',
    'sekizai.context_processors.sekizai',
    'django.core.context_processors.static',
    'cms.context_processors.cms_settings'
            ],
            'loaders': [
                'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
    'django.template.loaders.eggs.Loader'
            ],
        },
    },
]


MIDDLEWARE_CLASSES = (
    'cms.middleware.utils.ApphookReloadMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.locale.LocaleMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'cms.middleware.user.CurrentUserMiddleware',
    'cms.middleware.page.CurrentPageMiddleware',
    'cms.middleware.toolbar.ToolbarMiddleware',
    'cms.middleware.language.LanguageCookieMiddleware',
    'django_user_agents.middleware.UserAgentMiddleware'
)

INSTALLED_APPS = (
    'djangocms_admin_style',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.admin',
    'django.contrib.sites',
    'django.contrib.sitemaps',
    'django.contrib.staticfiles',
    'django.contrib.messages',
    'cms',
    'menus',
    'sekizai',
    'treebeard',
    'djangocms_text_ckeditor',
    'filer',
    'easy_thumbnails',
    'djangocms_column',
    'djangocms_link',
    'cmsplugin_filer_file',
    'cmsplugin_filer_folder',
    'cmsplugin_filer_image',
    'cmsplugin_filer_utils',
    'djangocms_style',
    'djangocms_snippet',
    'djangocms_googlemap',
    'djangocms_video',
    'disn',
    'account',
    'invest',
    'book',
    'testapp',
    'djangocms_forms',
    'django_user_agents',
    'django_extensions',
)

# Cache backend is optional, but recommended to speed up user agent parsing
# CACHES = {
#     'default': {
#         'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
#         'LOCATION': '127.0.0.1:11211',
#     }
# }

# https://django-redis-chs.readthedocs.io/zh_CN/latest/
def KEY_FUNCTION(key, key_prefix, version):
    return "ztmcache:" + key

CACHES = {
    'default': {
        'BACKEND': 'django_redis.cache.RedisCache',
        # 'LOCATION': 'redis://:Schenker123@127.0.0.1:6379/0',
        'LOCATION': redis_url,
        'OPTIONS': {
            "CLIENT_CLASS": 'django_redis.client.DefaultClient',
            # 'PASSWORD': '123456',
            "SOCKET_CONNECT_TIMEOUT": 5,  # in seconds
            "SOCKET_TIMEOUT": 5,  # in seconds
            "COMPRESSOR": "django_redis.compressors.zlib.ZlibCompressor",
            "CONNECTION_POOL_KWARGS": {"max_connections": 50}
        },
        'KEY_FUNCTION': KEY_FUNCTION,
    }
}

SESSION_ENGINE = "django.contrib.sessions.backends.cache"
SESSION_CACHE_ALIAS = "default"


# Name of cache backend to cache user agents. If it not specified default
# cache alias will be used. Set to `None` to disable caching.
USER_AGENTS_CACHE = 'default'

LANGUAGES = (
    ## Customize this
    ('zh', gettext('zh')),
)

CMS_LANGUAGES = {
    ## Customize this
    'default': {
        'public': True,
        'hide_untranslated': False,
        'redirect_on_fallback': True,
    },
    1: [
        {
            'public': True,
            'code': 'zh',
            'hide_untranslated': False,
            'name': gettext('zh'),
            'redirect_on_fallback': True,
        },
    ],
}

CMS_TEMPLATES = (
    ## Customize this
    ('base.html', '基础模板'),
    ('pc/base.html', 'PC基础模板'),
    ('pc/home.html', 'PC首页模板'),
    ('wap/base.html','WAP基础模版'),
    ('wap/home.html','WAP首页模版'),
    ('weixin/base.html', '微信基础模版'),
    ('weixin/content_base.html', '微信内容模版'),
)

CMS_PERMISSION = True

CMS_PLACEHOLDER_CONF = {}


if socket.gethostname() == PROD_SERVER_HOST_NAME:
    DATABASES = {
        'default': {
            'ENGINE' : 'django.db.backends.mysql',
            'NAME' : 'disn',
            'USER': 'root',
            'PASSWORD': 'qwer1234',
            'HOST': '127.0.0.1',                # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
            'PORT': '3306',                     # Set to empty string for default.
        }
    }
    print ('Prod Server connectted to MySQL server.')
elif socket.gethostname() in TST_SERVER_HOST_NAME:
    DATABASES = {
        'default': {
            'ENGINE' : 'django.db.backends.mysql',
            'NAME' : 'disntst',
            'USER': 'disntst',
            'PASSWORD': 'disntst123',
            'HOST': '127.0.0.1',                # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
            'PORT': '3306',                     # Set to empty string for default.
        }
    }
    print ('Test Server connectted to MySQL server.')
else:
    if socket.gethostname() in DEV_HOST_NAME:
        DATABASES = {
            'default': {
                'ENGINE' : 'django.db.backends.mysql',
                'NAME' : 'disndev',
                'USER': 'disndev',
                'PASSWORD': 'disndev123',
                'HOST': 'tst.disndev.cn',                # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
                'PORT': '3366',                       # Set to empty string for default.
            }
        }
        print ('DEV Server connectted to dev MySQL server.')
    else:
        DATABASES = {
            'default': {
                'CONN_MAX_AGE': 0,
                'ENGINE': 'django.db.backends.sqlite3',
                'HOST': 'localhost',
                'NAME': 'disn.db',
                'PASSWORD': '',
                'PORT': '',
                'USER': ''
            }
        }
        print ('DEV Server connected to local sqlite dabase.')


MIGRATION_MODULES = {

}

THUMBNAIL_PROCESSORS = (
    'easy_thumbnails.processors.colorspace',
    'easy_thumbnails.processors.autocrop',
    'filer.thumbnail_processors.scale_and_crop_with_subject_location',
    'easy_thumbnails.processors.filters'
)

LOGGING = {
    'version': 1,
    'formatters': {
        'simple': {
            'format': '%(levelname)s | %(message)s'
        },
    },
    'handlers': {
        'console':{
            'level': 'INFO',
            'class': 'logging.StreamHandler',
            'formatter': 'simple'
        },
    },
    'loggers': {
        'django.request': {
            'handlers': ['console', ],
            'level': 'INFO',
            'propagate': True,
        },
    },
}

# configuration for jupyter
NOTEBOOK_ARGUMENTS = [
    # exposes IP and port
    '--ip=0.0.0.0',
    '--port=8888',
    # disables the browser
    '--no-browser',
    '--allow-root',
]

AUTH_PROFILE_MODULE = 'account.UserProfile'
